package com.g4m.baselib.tool;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Md5加密
 * Created on 2019-01-26
 * <p>Copyright 2008-2019 snsndk.com</p>
 */
public class Md5 {

    private static final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte bt : b) {
            sb.append(byteToHexString(bt));
        }
        return sb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    /**
     * md5加密
     *
     * @param origin 要加密的字符串
     * @return 加密结果
     */
    public static String md5Encode(String origin) {
        try {
            MessageDigest md = MessageDigest.getInstance("Md5");
            return byteArrayToHexString(md.digest(origin
                    .getBytes()));
        } catch (NoSuchAlgorithmException ignore) {
        }
        return origin;
    }

}